<!-- new publish step -->
<div>
    {#if publishHed}
    <h2 class="pad-top">{@html publishHed}</h2>
    {/if} {#if publishIntro}
    <p>{@html publishIntro}</p>
    {:else} {#if published}
    <p>{@html __('publish / republish-intro') }</p>
    {:else}
    <p style="margin-bottom: 20px">{@html __('publish / publish-intro') }</p>
    {/if} {/if}

    <button disabled="{ publishing }" on:click="publish()" class="btn-publish btn btn-primary btn-large {published?'':'btn-first-publish'}">
        {#if published}
        <span class="re-publish"
            ><i class="fa fa-fw fa-refresh {publishing ? 'fa-spin' : ''}"></i> <span class="title">{ __('publish / republish-btn') }</span></span
        >
        {:else}
        <span class="publish"
            ><i class="fa fa-fw {publishing ? 'fa-refresh fa-spin' : 'fa-cloud-upload'}"></i>
            <span class="title">{ __('publish / publish-btn') }</span></span
        >
        {/if}
    </button>

    {#if !published}
    <div class="publish-intro">
        <div class="arrow">
            <i class="fa fa-chevron-left"></i>
        </div>
        <div class="text">
            {@html __('publish / publish-btn-intro') }
        </div>
    </div>
    {/if} {#if needs_republish && !publishing}
    <div class="btn-aside alert">
        {@html __('publish / republish-alert') }
    </div>
    {/if} {#if published && !needs_republish && progress === 1 && !publishing}
    <div class="alert alert-success">
        {@html __('publish / publish-success') }
    </div>
    {/if} {#if publish_error}
    <div class="alert alert-error">
        {@html publish_error }
    </div>
    {/if} {#if publishing}
    <div class="alert {progress < 1 ? 'alert-info' : 'alert-success'} publishing">
        { __("publish / progress / please-wait") }
        <div class="progress progress-striped active">
            <div class="bar {progress < 1 ? '' : 'bar-success'}" ref:bar />
        </div>
    </div>
    {/if}

    <div style="margin-top:30px" class="{published?'':'inactive'}">
        <h2>{@html __('publish / share-embed') }</h2>
        <div class="block">
            <i class="icon fa fa-link fa-fw"></i>
            <div class="ctrls">
                <div class="h">
                    <b>{@html __('publish / share-url') }</b>
                    <div class="embed-options">
                        <label class="radio">
                            <input bind:group="shareurl_type" value="default" type="radio" name="url-type" />
                            {@html __('publish / share-url / fullscreen') }
                        </label>
                        {#each plugin_shareurls as tpl}
                        <label class="radio"
                            ><input bind:group="shareurl_type" value="{tpl.id}" type="radio" name="url-type" /> {@html tpl.name}</label
                        >
                        {/each}
                    </div>
                </div>
                <div class="inpt">
                    <a target="_blank" class="share-url" href="{shareUrl}">{shareUrl}</a>
                </div>
            </div>
            <Help>
                <div>{@html __('publish / help / share-url') }</div>
            </Help>
        </div>

        <div class="block">
            <i class="icon fa fa-code fa-fw"></i>
            <div class="ctrls">
                <div class="h">
                    <b>{@html __('publish / embed') }</b>
                    <div class="embed-options">
                        {#each embed_templates as tpl}
                        <label class="radio"><input type="radio" bind:group="embed_type" value="{tpl.id}" /> {@html tpl.title }</label>
                        {/each}
                    </div>
                </div>
                <div class="inpt">
                    <input ref:embedInput type="text" class="input embed-code" readonly value="{embedCode}" />
                    <button class="btn btn-copy" on:click="copy(embedCode)" title="copy"><i class="fa fa-copy"></i> { __('publish / copy') }</button>
                    <div class="copy-success {copy_success ? 'show':''}">
                        { __('publish / copy-success') }
                    </div>
                </div>
            </div>
            <Help>
                <div>
                    {@html __('publish / embed / help') } {#each embed_templates.slice(2) as tpl}
                    <div><b>{tpl.title}:</b> {@html tpl.text}</div>
                    {/each}
                </div>
            </Help>
        </div>
    </div>

    <!-- BEFORE EXPORT -->
    <svelte:component this="{beforeExport}" />

    <!-- EXPORT -->
    <div class="export-and-duplicate">
        <div>
            <h2 class="pad-top">{@html exportHed}</h2>
            {#if exportIntro}
            <p>{@html exportIntro}</p>
            {/if}
        </div>

        <ul class="chart-actions">
            {#each sortedChartActions as action} {#if action}
            <li class="action action-{action.id} {action.class||''} {action.id == active_action ? 'active':''}">
                <a on:click="select(action, event)" role="button" href="{action.url ? action.url : '#'+action.id}">
                    <i class="fa fa-{action.icon}"></i><span class="title">{@html action.title}</span>
                </a>
                {#if action.banner && action.banner.text != "FALSE" && action.banner.text != "-"}
                <div class="banner" style="{action.banner.style}">{action.banner.text}</div>
                {/if}
            </li>
            {/if} {/each}
        </ul>

        <svelte:component ref:action this="{Action}" visible="{true}" show="{true}" />
    </div>
</div>

<style>
    .btn-publish {
        border-color: #1d81a2 !important;
        box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.25);
        line-height: 20px;
        padding: 15px;
    }

    .btn-publish + .alert {
        margin-top: 10px;
    }

    .btn-first-publish {
        text-align: center;
        width: 150px;
        vertical-align: middle;
        padding: 15px 0 15px;
    }

    .btn-publish i.fa {
        font-size: 20px;
    }
    .btn-first-publish i.fa {
        font-size: 32px;
        display: block;
        margin: 5px auto;
    }

    .btn-first-publish .title {
        display: block;
        text-align: center;
        font-size: 18px;
        line-height: 22px;
        padding: 5px 20px 0px 20px;
    }
    .publish-intro {
        display: inline-block;
        font-size: 18px !important;
        line-height: 22px;
    }

    .publish-intro .arrow {
        vertical-align: middle;
        display: inline-block;
        padding: 15px;
    }
    .publish-intro .text {
        vertical-align: middle;
        display: inline-block;
        width: 200px;
    }
    @media (max-width: 1200px) {
        .publish-intro {
            font-size: 15px;
        }
        .publish-intro .text {
            vertical-align: middle;
            display: inline-block;
            width: 140px;
            line-height: 18px;
            font-size: 15px;
        }
    }

    div.progress {
        margin-top: 8px;
        margin-bottom: 4px;
    }
    input[type='radio'] {
        vertical-align: baseline !important;
        margin-left: -20px !important;
    }
    a.share-url {
        font-size: 18px;
    }
    .btn-aside.alert {
        margin-left: 0;
        margin-top: 7px;
        max-width: 100%;
    }

    .copy-success {
        font-size: 11px;
        color: #9c9;
        font-style: italic;
        opacity: 0;
        pointer-events: none;
        transition: opacity 5s ease-in;
        margin-top: -10px;
        position: absolute;
    }
    .copy-success.show {
        opacity: 1;
        transition: none;
    }
    .embed-options {
        display: inline-block;
    }
</style>

<script>
    /* eslint camelcase: "off" */

    import Help from '../editor/Help.html';
    import Action from './Action.html';

    import { __ } from '../shared/l10n';
    import { trackEvent } from '../shared/analytics';
    import { getJSON, postJSON, loadScript, loadStylesheet } from '../shared/utils';
    import computeEmbedHeights from './compute-embed-heights';

    let fakeProgress = 0;
    let initial_auto_publish = true;

    export default {
        components: { Help },
        data() {
            return {
                active_action: '',
                embed_templates: [],
                plugin_shareurls: [],
                published: false,
                publishing: false,
                needs_republish: false,
                publish_error: false,
                auto_publish: false,
                progress: 0,
                shareurl_type: 'default',
                embed_type: 'responsive',
                copy_success: false,
                Action,
                chartActions: [
                    {
                        id: 'duplicate',
                        icon: 'code-fork',
                        title: __('Duplicate'),
                        order: 500,
                        action: 'duplicate'
                    }
                ],
                publishHed: '',
                publishIntro: '',
                beforeExport: null,
                exportHed: __('publish / export-duplicate'),
                exportIntro: __('publish / export-duplicate / intro'),
                embedCode: ''
            };
        },
        computed: {
            shareUrl({ shareurl_type, $id, $publicUrl, plugin_shareurls, published }) {
                if (!published) return 'https://www.datawrapper.de/...';
                if (shareurl_type === 'default') return $publicUrl;
                let url = '';
                plugin_shareurls.forEach(t => {
                    if (t.id === shareurl_type) url = t.url.replace(/%chart_id%/g, $id);
                });
                return url;
            },

            sortedChartActions({ chartActions, $actions }) {
                return chartActions
                    .concat($actions)
                    .filter(a => a.id !== 'publish-s3')
                    .sort((a, b) => a.order - b.order);
            }
        },
        helpers: { __ },
        methods: {
            publish() {
                this.set({
                    publishing: true,
                    progress: 0,
                    publish_error: false
                });

                const chart = this.store;
                // generate embed codes
                chart.setMetadata('publish.embed-heights', computeEmbedHeights(chart, this.get().embed_templates));

                // save embed heights and wait until it's done before
                // we start to publish the chart
                trackEvent('Chart Editor', 'publish');

                chart.store(() => {
                    // publish chart
                    postJSON(`/api/charts/${chart.get().id}/publish`, null, res => {
                        if (res.status === 'ok') {
                            this.publishFinished(res.data);
                            trackEvent('Chart Editor', 'publish-success');
                        } else {
                            trackEvent('Chart Editor', 'publish-error', res.message);
                            this.set({
                                publish_error: res.message
                            });
                        }
                    });
                    fakeProgress = 0;
                    this.updateStatus();
                });
            },

            updateProgressBar(p) {
                if (this.refs.bar) {
                    this.refs.bar.style.width = (p * 100).toFixed() + '%';
                }
            },

            updateStatus() {
                const chart = this.store;
                fakeProgress += 0.05;
                getJSON(`/api/charts/${chart.get().id}/publish/status`, res => {
                    if (res) {
                        res = +res / 100 + fakeProgress;
                        this.set({ progress: Math.min(1, res) });
                    }
                    if (this.get().publishing) {
                        setTimeout(() => {
                            this.updateStatus();
                        }, 400);
                    }
                });
            },

            publishFinished(chartInfo) {
                this.set({
                    progress: 1,
                    published: true,
                    needs_republish: false
                });
                this.store.set({
                    lastEditStep: 5
                });
                setTimeout(() => this.set({ publishing: false }), 500);
                this.store.set(chartInfo);
            },

            setEmbedCode() {
                const chart = this.store;
                const state = this.get();
                if (!state) return;
                const embedType = state.embed_type ? `embed-method-${state.embed_type}` : null;

                const { publicUrl } = chart.get();
                const embedCodes = chart.getMetadata('publish.embed-codes');
                const embedHeight = chart.getMetadata('publish.embed-height');

                this.set({
                    embedCode:
                        embedCodes && embedCodes[embedType]
                            ? embedCodes[embedType]
                            : `<iframe src="${publicUrl}" width="100%" height="${embedHeight}" scrolling="no" frameborder="0" allowtransparency="true"></iframe>`
                });
            },

            copy() {
                const me = this;
                me.refs.embedInput.select();
                try {
                    var successful = document.execCommand('copy');
                    if (successful) {
                        trackEvent('Chart Editor', 'embedcode-copy');
                        me.set({ copy_success: true });
                        setTimeout(() => me.set({ copy_success: false }), 300);
                    }
                } catch (err) {
                    // console.log('Oops, unable to copy');
                }
            },

            select(action, event) {
                event.preventDefault();
                // set hash which is used to show the action module
                window.location.hash = action.id;

                const { active_action } = this.get();
                if (action.id === active_action) {
                    // unselect current action
                    return this.set({ active_action: '', Action });
                }
                this.set({ active_action: action.id });
                if (action.mod) {
                    if (action.mod.App) {
                        this.set({ Action: action.mod.App });
                    } else {
                        // todo: show loading indicator
                        this.set({ Action });
                        this.refs.action.set({ loading: true });
                        if (action.mod.css) {
                            loadStylesheet(action.mod.css);
                        }
                        loadScript(action.mod.src, () => {
                            setTimeout(() => {
                                require([action.mod.id], mod => {
                                    // todo: HIDE loading indicator
                                    Object.assign(action.mod, mod);
                                    this.set({ Action: action.mod.App });
                                    if (mod.init) mod.init(this.refs.action);
                                    if (action.mod.data) this.refs.action.set(action.mod.data);
                                });
                            }, 200);
                        });
                    }
                } else if (action.action && this[action.action]) {
                    this.set({ Action });
                    this[action.action]();
                } else if (typeof action.action === 'function') {
                    this.set({ Action });
                    action.action();
                }
            },

            duplicate() {
                const { id } = this.store.get();
                trackEvent('Chart Editor', 'duplicate');
                postJSON(`/api/charts/${id}/copy`, null, res => {
                    if (res.status === 'ok') {
                        // redirect to copied chart
                        window.location.href = `/edit/${res.data.id}/visualize`;
                    } else {
                        console.warn(res);
                    }
                });
            }
        },

        oncreate() {
            const { lastEditStep } = this.store.get();
            this.set({ published: lastEditStep > 4 });
            // store reference to publish step
            window.dw.backend.fire('edit.publish.oncreate', this);
            // watch changes
            this.setEmbedCode();
            const chart = this.store;
            chart.observeDeep('metadata.publish.embed-codes', () => this.setEmbedCode());
            chart.observeDeep('metadata.publish.embed-height', () => this.setEmbedCode());
            chart.observeDeep('publicUrl', () => this.setEmbedCode());
        },

        onstate({ changed, current }) {
            const userDataReady = window.dw && window.dw.backend && window.dw.backend.setUserData;
            if (changed.publishing) {
                if (current.publishing) this.updateProgressBar(current.progress);
            }
            if (changed.progress) {
                this.updateProgressBar(current.progress);
            }
            if (changed.embed_type && userDataReady) {
                const data = window.dw.backend.__userData;
                if (!current.embed_type || !data) return;
                data.embed_type = current.embed_type;
                window.dw.backend.setUserData(data);
            }
            if (changed.embed_type) {
                this.setEmbedCode();
            }
            if (changed.shareurl_type && userDataReady) {
                const data = window.dw.backend.__userData;
                if (!current.shareurl_type || !data) return;
                data.shareurl_type = current.shareurl_type;
                window.dw.backend.setUserData(data);
            }
            if (changed.published) {
                const publishStep = window.document.querySelector('.dw-create-publish .publish-step');
                if (publishStep) {
                    publishStep.classList[current.published ? 'add' : 'remove']('is-published');
                }
            }
            if (changed.auto_publish) {
                if (current.auto_publish && initial_auto_publish) {
                    this.publish();
                    initial_auto_publish = false;
                    window.history.replaceState('', '', window.location.pathname);
                }
            }
        }
    };
</script>
